/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

/*
 * @Descripttion:
 * @version: 1.0.0
 * @Author: YinJianFeng
 * @Date: 2024-04-08 09:35:09
 */
import { BaseCommand, cadAppLog, cmdInvoker, CMEVENTS } from '@amcax/base';
import { sketchStore } from '@app-base/common/utils/sketchTools/useSketchStore';
import {
  exitSketcherMethod,
  parseAxis,
  resetRenderSketch,
} from '@app-cad/common/utils';
import { sketchEventCenter } from '@app-cad/environments/nextcad/events/SketchEventCenter';
import { CmdManager, cmdMgr } from '@app-cad/manager/CmdManager';
import { docMgr, userEvents } from '@app-cad/module';
import { wsApi } from '@app-cad/server';

export const cmdUndo: BaseCommand = {
  id: 'CmdUndo',
  label: 'command.undo',
  icon: 'commands/feature/undo',
  help: {
    remark: 'tips.undo',
    // preview: '/help/Undo.gif'
  },
  noHighlight: true,

  subscribeDisabled: (setDisabled: (disabled: boolean) => void) => {
    const listener = (cmdMgr: CmdManager) => {
      cadAppLog('undo...[canUndo]', cmdMgr.canUndo);
      setDisabled(!cmdMgr.canUndo);
    };
    userEvents.on(CMEVENTS.CMD_MGR_EXECUTED, listener);
    userEvents.delete(CMEVENTS.CMD_SKETCH_UNDO);
    userEvents.on(CMEVENTS.CMD_SKETCH_UNDO, async () => {
      if (cmdMgr.canUndo) {
        await cmdInvoker.invokeCmd(cmdUndo);
      }
    });
    return () => userEvents.off(CMEVENTS.CMD_MGR_EXECUTED, listener);
  },

  invoke: async () => {
    try {
      const sketchId: string = sketchEventCenter().getSketchInfo().sketchId;
      if (sketchId && cmdMgr.canUndo) {
        const data = await wsApi.getSketchCurves(sketchId);
        if (data.curves.length === 7) {
          await exitSketcherMethod(sketchId);
        } else {
          await cmdMgr.undo();

          const data = await wsApi.getSketchCurves(sketchId);
          sketchStore
            .getState()
            .updateSketchCurves(data?.curves?.map(parseAxis));
          await resetRenderSketch(sketchId);
          await docMgr.loadSketchChildren(sketchId);
        }
      }
    } catch (error) {
      /* empty */
    }
  },
};
